package com.itheima.comment.server.impl;

import com.heima.model.common.VO.ApCommentRepayVO;
import com.heima.model.common.VO.ApCommentVo;
import com.heima.model.common.comment.pojos.ApComment;
import com.heima.model.common.comment.pojos.ApCommentLike;
import com.heima.model.common.comment.pojos.ApCommentRepay;
import com.heima.model.common.comment.pojos.ApCommentRepayLike;
import com.heima.model.common.dtos.CommentRepayDTO;
import com.heima.model.common.dtos.CommentRepayLikeDTO;
import com.heima.model.common.dtos.CommentRepaySaveDTO;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.common.threadlocal.AppThreadLocalUtils;
import com.heima.model.common.user.pojo.ApUser;
import com.itheima.aliyun.scan.GreenScan;
import com.itheima.aliyun.scan.ScanResult;
import com.itheima.comment.server.CommentRepayService;
import com.itheima.common.exception.CustException;
import com.itheima.feigns.UserFeign;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
@Service
@Slf4j
public class CommentRepayServiceImpl implements CommentRepayService {
    @Autowired
    private GreenScan greenScan;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private MongoTemplate mongoTemplate;
    @Autowired
    RedissonClient redisson;

    @Override
    public ResponseResult loadCommentRepay(CommentRepayDTO dto) {
        //根据条件查询评论列表
        Date minDate = dto.getMinDate();
        if (minDate==null){
            minDate=new Date();
        }
        Integer size = dto.getSize();
        if (size==null || size==0){
            size=10;
        }
        Query query = Query.query(Criteria.where("commentId").is(dto.getCommentId()).and("createdTime").lt(dto.getMinDate()));
        Pageable pageable = PageRequest.of(0,size);  // page=0 第一页
        query.with(pageable);
        Sort sort = Sort.by(Sort.Direction.DESC,"createdTime");
        query.with(sort);// 排序
        List<ApCommentRepay> apCommentRepays = mongoTemplate.find(query, ApCommentRepay.class);
        //判断用户是否登录
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            //没有登录直接返回评论列表
            return ResponseResult.okResult(apCommentRepays);
        }
        //登录了进行转换
        ArrayList<ApCommentRepayVO> apCommentRepayVos = new ArrayList<>();
        for (ApCommentRepay apCommentRepay : apCommentRepays) {

            ApCommentRepayVO apCommentRepayVO = new ApCommentRepayVO();
            BeanUtils.copyProperties(apCommentRepay, apCommentRepayVO);
            //查询用户点赞过哪些评论
            ApCommentRepayLike one = mongoTemplate.findOne(Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(apCommentRepay.getId()).and("operation").is((short) 0)), ApCommentRepayLike.class);
            if (one!=null){
                apCommentRepayVO.setOperation((short)0);
            }
            apCommentRepayVos.add(apCommentRepayVO);
        }
        return ResponseResult.okResult(apCommentRepayVos);
    }

    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDTO dto) {
        String content = dto.getContent();
        //远程查询当前登录用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        ApUser apUser = userFeign.findUserById(user.getId()).getData();
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        //阿里云检测内容是否违规
        try {
            ScanResult scanResult = greenScan.greenTextScan(content);
            String suggestion = scanResult.getSuggestion();
            if (suggestion.equals("block")){//评论内容违规  替换为**
                String filteredContent = scanResult.getFilteredContent();
                apCommentRepay.setAuthorId(user.getId());
                apCommentRepay.setAuthorName(apUser.getName());
                apCommentRepay.setCommentId(dto.getCommentId());
                apCommentRepay.setContent(filteredContent);
                apCommentRepay.setLikes(0);
                apCommentRepay.setCreatedTime(new Date());
            }else{
                //内容没有问题
                apCommentRepay.setAuthorId(user.getId());
                apCommentRepay.setAuthorName(apUser.getName());
                apCommentRepay.setCommentId(dto.getCommentId());
                apCommentRepay.setContent(content);
                apCommentRepay.setLikes(0);
                apCommentRepay.setCreatedTime(new Date());
            }



        } catch (Exception e) {
            e.printStackTrace();
            log.error("阿里云文本审核出现异常 , 原因:{}",e.getMessage());
        }
        //根据评论id查询评论信息是否存在
        ApComment one = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(dto.getCommentId())), ApComment.class);
        if (one==null){
            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"评论去二次元了,你也要去吗,我tm创死你");
        }

        //保存回复
        ApCommentRepay save = mongoTemplate.save(apCommentRepay);
        //修改评论中的
        Update update = new Update();
        update.set("reply",one.getReply()+1);
        mongoTemplate.updateMulti(Query.query(Criteria.where("_id").is(dto.getCommentId())),update,ApComment.class);
        return ResponseResult.okResult();

    }

    @Override
    public ResponseResult saveCommentRepayLike(CommentRepayLikeDTO dto) {
        //获得用户id
        ApUser user = AppThreadLocalUtils.getUser();
        if (user==null){
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        //校验回复信息是否存在
        ApCommentRepay apCommentRepay = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(dto.getCommentRepayId())), ApCommentRepay.class);
//        if (one==null){
//            CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"回复去二次元了,你也要去吗,我tm创死你");
//        }

//        ApComment apComment = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(dto.getCommentId())), ApComment.class);
        RLock lock =redisson.getLock("Rlikes-lock");
        lock.lock();
        try {
            if (apCommentRepay==null){
                CustException.cust(AppHttpCodeEnum.DATA_NOT_EXIST,"评论去二次元了,你也要去吗,我开车创死你");
            }
            if (dto.getOperation().equals((short)0)){//点赞操作
                //判断是否已经点赞
                ApCommentRepayLike apCommentRepayLike = mongoTemplate.findOne(Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()).and("operation").is((short) 0)), ApCommentRepayLike.class);
                if (apCommentRepayLike==null){
                    //保存点赞信息
                    apCommentRepayLike = new ApCommentRepayLike();
                    apCommentRepayLike.setCommentRepayId(dto.getCommentRepayId());
                    apCommentRepayLike.setOperation((short)0);
                    apCommentRepayLike.setAuthorId(user.getId());
                    ApCommentRepayLike save = mongoTemplate.save(apCommentRepayLike);
                    //修改评论信息的点赞数量+1
                    Update update = new Update();
                    update.set("likes",apCommentRepay.getLikes()+1);
                    mongoTemplate.updateMulti(Query.query(Criteria.where("_id").is(dto.getCommentRepayId())),update,ApCommentRepay.class);
                }
    //            else {
    //                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW,"别点那么快嘛,人家傻fufu反应不过来");
    //            }
            }else {
                //删除点赞信息
                mongoTemplate.remove(Query.query(Criteria.where("authorId").is(user.getId()).and("commentRepayId").is(dto.getCommentRepayId()).and("operation").is((short) 0)), ApCommentRepayLike.class);
                //修改评论信息的点赞数量-1
                Update update = new Update();
                update.set("likes",apCommentRepay.getLikes()-1);
                mongoTemplate.updateMulti(Query.query(Criteria.where("_id").is(dto.getCommentRepayId())),update,ApCommentRepay.class);
            }
        } finally {
            lock.unlock();
        }
        //最后再查一次点赞数量
        ApCommentRepay commentRepayLast = mongoTemplate.findOne(Query.query(Criteria.where("_id").is(dto.getCommentRepayId())), ApCommentRepay.class);
        Integer likes = commentRepayLast.getLikes();
        HashMap<String, Integer> resultMap = new HashMap<>();
        resultMap.put("likes",likes);
        return ResponseResult.okResult(resultMap);
    }
}
